from flask import Blueprint, request
from time import time

from file.model import File
from file.model import db

from database import R

file_blueprint = Blueprint('file', __name__)

def getUid():
    uid = R.get(request.headers.get('token'))
    if uid is None:
        return None
    else:
        return uid


@file_blueprint.before_request
def before_eq():
    if getUid() is None:
        return {
                   'errmsg': 'token expired'
               }, 401


@file_blueprint.route('/upload', methods=['POST'])
def upload():
    if request.method == 'POST':
        origin_name = request.form.get('origin_name')
        print(origin_name)  # 原始文件名

        f = request.files['file']
        # 自定义拼接虚假文件名
        fake_name = str(int(time())) + '_' + 'userid_' + str(int(getUid())) +  '.' + f.filename.split('.')[1]
        print(fake_name)
        f.save('file/uploads/' + fake_name)

        file = File(origin_name=origin_name, after_name=fake_name)
        db.session.add(file)
        db.session.flush()  # 拿到文件ID 返回给前端
        db.session.commit()

        return {
            'fid': file.id,
            'msg': '上传文件成功.'
        }, 200